<!--
    @title index.vue
    @description TODO 签章管理
    @author yuzhenhan
    @date 2021/02/23 11:56:08
-->
<template>
  <div>
    <el-card class="box-card" shadow="never">
      <div slot="header" class="clearfi">
        <span>签名管理</span>
      </div>
      <div class="text item" v-if="!data.display">
        <div class="hello">
          <img :src="data.sign" />
        </div>
      </div>
      <div class="btm" v-if="!data.display">
        <el-button type="primary" @click="deleteSignature">重写</el-button>
        <el-button icon="el-icon-download" type="primary" @click="download"
          >下载</el-button
        >
      </div>
    </el-card>

    <div v-if="data.display" class="box-card" shadow="never">
      <div class="text item">
        <div class="hello">
          <ElesignCode ref="signCode1" :datas="datas" :pen="pen" />
        </div>
      </div>
      <div slot="header" class="clearfix">
        <span>请设置您的签名</span>

        <el-button @click="rewrite">重写</el-button>
        <el-button @click="changePen">切换笔</el-button>

        <el-upload
          class="upload-demo inline-block"
          action="#"
          :on-change="handleChange"
          :file-list="fileList"
          accept=".png"
          :auto-upload="false"
          :show-file-list='false'
        >
          <el-button>上传签名</el-button>
        </el-upload>
        <el-button type="danger" plain @click="cancel">取消</el-button>
        <el-button type="primary" @click="saveData">提交</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import ElesignCode from 'elesigncode/lib/core/elesigncode'
import { saveSignature, getSignature } from '@/api/uc/signature'
import { uploadPng } from '@/api/uc/signature.js'

export default {
  name: 'signature',
  components: {
    ElesignCode
  },
  data() {
    return {
      pen: 'writing',
      datas: {
        data: [],
        color: '#333',
        lineWidth: 4,
        bgColor: '-1',
        pen: 'default',
        writingMaxLine: 20,
        writingMinLine: 10
      },
      data: {
        signatureId: '',
        display: true,
        status: 0,
        sign: ''
      },
      fileList: []
    }
  },
  mounted() {
    this.getData()
  },
  methods: {
    download() {
      let imgData = this.data.sign //这里放需要下载的base64
      console.log(imgData)
      this.downloadFile('个人签章.png', imgData)
    },
    downloadFile(fileName, content) {
      let aLink = document.createElement('a')
      let blob = this.base64ToBlob(content) //new Blob([content]);

      let evt = document.createEvent('HTMLEvents')
      evt.initEvent('click', true, true) //initEvent 不加后两个参数在FF下会报错  事件类型，是否冒泡，是否阻止浏览器的默认行为
      aLink.download = fileName
      aLink.href = URL.createObjectURL(blob)

      // aLink.dispatchEvent(evt);
      aLink.click()
    },
    //base64转blob
    base64ToBlob(code) {
      let parts = code.split(';base64,')
      let contentType = parts[0].split(':')[1]
      let raw = window.atob(parts[1])
      let rawLength = raw.length

      let uInt8Array = new Uint8Array(rawLength)

      for (let i = 0; i < rawLength; ++i) {
        uInt8Array[i] = raw.charCodeAt(i)
      }
      return new Blob([uInt8Array], { type: contentType })
    },
    cancel() {
      this.data.display = false
      this.data.datas = []
    },
    deleteSignature() {
      this.data.datas = []
      this.data.display = true
    },
    changePen() {
      if (this.pen !== 'writing') {
        this.pen = 'writing'
      } else {
        this.pen = 'default'
      }
    },
    rewrite() {
      this.datas.data = []
    },
    log(msg) {
      return console.log(msg)
    },
    saveData() {
      var datas = JSON.parse(this.$refs.signCode1.toJson())
      console.log(datas)
      if (datas.data.length > 0) {
        var dataurl = this.$refs.signCode1.toPng()
        var data = {
          sign: dataurl,
          signatureId: this.data.signatureId
        }
        saveSignature(data).then((res) => {
          if (res.code === 1) {
            this.$message.success('保存成功')
            this.$router.go(0)
          }
        })
      } else {
        this.$message.error('未识别到书写数据')
      }
    },
    getData: function () {
      getSignature({}).then((res) => {
        if (res.data != null) {
          console.log(res.data, '图片')
          this.data.display = false
          this.data.sign = res.data.sign
          this.data.signatureId = res.data.signatureId
        }
      })
    },
    // 上传签名
    handleChange(file, fileList) {
      this.getBase64(file.raw).then((res) => {
        console.log(res,'sososoososos')
        uploadPng({sign:res}).then(res=>{
          if(res.code){
            this.$message.success('上传成功')
             this.$router.go(0)
          }else{
            this.$message.error('上传失败,上传图片为PNG格式最大为3M')
          }
        })
      })

    },
    getBase64(file) {
      return new Promise(function (resolve, reject) {
        let reader = new FileReader()
        let imgResult = ''
        reader.readAsDataURL(file)
        reader.onload = function () {
          imgResult = reader.result
        }
        reader.onerror = function (error) {
          reject(error)
        }
        reader.onloadend = function () {
          resolve(imgResult)
        }
      })
    }
  }
}
</script>

<style scoped>
.btm {
  margin-top: 20px;
  text-align: left;
  margin-right: 20px;
}
.box-card {
  border: 0px solid #000;
}
.hello {
  width: 50%;
  /* margin: 0 auto; */
  height: 300px;
  border: 1px solid #e6eaee;
}
.hello img {
  width: 100%;
  height: 100%;
}
.clearfix {
  margin-right: 20px;
  margin-top: 20px;
  text-align: left;
}
.box-card /deep/ .el-card__body {
  padding: 0px;
}
.inline-block {
  display: inline-block;
  margin-left: 10px;
  margin-right: 10px;
}
</style>
